package com.test.springboot.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
public class UploadController {
	@Autowired
	private HttpServletRequest request;
	
	public static void main(String[] args) {
		String filename="abc..txt.jpg";
		int lastindex=filename.lastIndexOf(".");
		System.out.println(filename.substring(lastindex));
		System.out.println();
	}

	@RequestMapping("/download")
	public ResponseEntity download(String filename) throws IOException {
		//获取上传目录
		String uploadDir=new ClassPathResource("").getURL().getPath()+"static/upload/";
		System.out.println("uploadDir--->"+uploadDir);
		File file=new File(uploadDir+filename);
		HttpHeaders headers=new HttpHeaders();
		//设置下载文件的文件属性
		headers.setContentDispositionFormData("attachment",filename);
		//设置下载文件的类型为字节流
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		
		//下载文件
		ResponseEntity response=new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
		return response;
	}
	
	@GetMapping("/")
	public String toUpload(){
		return "upload";
	}

	@PostMapping("/upload")
	public String upload(@RequestParam("file1") MultipartFile mfile) throws IOException, InterruptedException {
		//part1 有效性验证
		if(mfile.isEmpty()){
			request.setAttribute("msg", "请选择要上传的文件");
			return "upload";
		}
		
		//part2 获取并创建上传目录
		String rootPath= new ClassPathResource("").getURL().getPath();
		String filePath=rootPath+"static/upload/";
		File dir=new File(filePath);
		if(!dir.exists()){
			dir.mkdirs();//创建上传目录
		}
		
		//part3 获取文件名称和类型
		String fname= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
		String ext=mfile.getOriginalFilename().substring(mfile.getOriginalFilename().lastIndexOf("."));
		String filename=fname+ext;
		
		System.out.println(filePath+filename);
		
		//part4 保存上传文件到对应磁盘目录中
		File file=new File(filePath+filename);
		mfile.transferTo(file);//保存文件
		
		request.setAttribute("filename", filename);
		return "show";
	}
	
	@PostMapping("/upload2")
	public String upload2(@RequestParam("filem") List<MultipartFile> mlist) throws IOException, InterruptedException {
		if(mlist==null || mlist.size()==0){
			request.setAttribute("msg", "请选择要上传的文件");
			return "upload";
		}
		
		List<String> fileList=new ArrayList<>();
		
		for (MultipartFile mfile : mlist) {
			
			Map<String,String> re=excuteUpload(mfile);
			if(re.get("flag").equals("error")){
				return re.get("msg");
			}
			
			fileList.add(re.get("msg"));
		}
		
		request.setAttribute("fileList", fileList);
		return "show2";
		
	}
	
	@PostMapping("/upload3")
	public String upload3(@RequestParam Map<String,MultipartFile> fmap) throws IOException, InterruptedException {
		if(fmap==null || fmap.size()==0){
			request.setAttribute("msg", "请选择要上传的文件");
			return "upload";
		}
		
		List<String> fileList=new ArrayList<>();
		
		Iterator<String> it = fmap.keySet().iterator();
		while(it.hasNext()){
			String nameFile=it.next();//获取map集合中的键名 file1  file2
			MultipartFile mfile=fmap.get(nameFile);
			
			Map<String,String> re=excuteUpload(mfile);
			if(re.get("flag").equals("error")){
				return re.get("msg");
			}
			
			fileList.add(re.get("msg"));
		}
		
		request.setAttribute("fileList", fileList);
		return "show2";
		
	}
	
	private Map excuteUpload(MultipartFile mfile) throws IOException {
		Map<String,String> result=new HashMap<>();
		//part1 有效性验证
		if(mfile.isEmpty()){
			request.setAttribute("msg", "请选择要上传的文件");
			result.put("flag", "error");
			result.put("msg", "upload");
			return result;
		}
		
		//part2 获取并创建上传目录
		String filePath= new ClassPathResource("").getURL().getPath()+File.separator+"static"+File.separator+"upload"+File.separator;
		File dir=new File(filePath);
		if(!dir.exists()){
			dir.mkdirs();//创建上传目录
		}
		
		//part3 获取文件名称和类型
		String fname= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
		String ext=mfile.getOriginalFilename().substring(mfile.getOriginalFilename().lastIndexOf("."));
		String filename=fname+ext;
		
		System.out.println(filePath+filename);
		
		//part4 保存上传文件到对应磁盘目录中
		File file=new File(filePath+filename);
		mfile.transferTo(file);//保存文件
		
		
		result.put("flag", "ok");
		result.put("msg", filename);
		
		return result;
	}
	
}
